
#-*- coding: UTF-8 -*-
'''
Created on Mar 7, 2011

@author: Juho Salmio
'''
import os.path


'''
Reads the logfile that growl has created and differentiates the song and artist
data to a different file
'''

def main():
    (artist,song) = parseGrowlLog()
    src = open(os.path.expanduser('~/Library/Logs/lastsong'),'w')
    src.write(song +'@' + artist)
    src.close()
    print song +'@' + artist

def parseGrowlLog():
    
    logfilepathsrc = open(os.path.expanduser('~/Library/Logs/Growl_logpath'),'r')
    logfilepath = logfilepathsrc.read()
    logfilepathsrc.close()
    
    src = open(logfilepath,"r")
    lines = src.readlines()
    src.close()
    
    lines.reverse()
    
    lastspotline = ""
    song = ''
    artist = ''
    justSongAndArtist = ''
    # Line to parse: Mar 6, 2011 10:39:25 PM Spotify: Human (The Killers
    for line in lines:
        if line.find('Spotify:') != -1:
            split = line.split('Spotify:')
            justSongAndArtist = split[1]
            break
    
    
    count = justSongAndArtist.count('(')
    
    #Basic case: Human (The Killers
    if count == 1:
        songAndArtistApart = justSongAndArtist.split(' (')
        song = songAndArtistApart[0]
        
        artist = songAndArtistApart[1]
       
        
    elif count == 2:
        #case brackets in artist name
        if justSongAndArtist.find(')') > find_nth(justSongAndArtist,'(', 2):
                songAndArtistApart = justSongAndArtist.split('(',1)
                song = songAndArtistApart[0]
                
                artist = songAndArtistApart[1]
                
        
        #case brackets in song name: Oxygene (Part IV) (Jean Michel Jarre
        else:
            
            splitindx = find_nth(justSongAndArtist, '(', 2)
            
            song = justSongAndArtist[:splitindx-1]
            artist = justSongAndArtist[splitindx+1:]
           
    
    #case brackets in both sides
    elif count == 3:
        splitindx = find_nth(justSongAndArtist,'(',2)
        song = justSongAndArtist[splitindx-1:]
        artist = justSongAndArtist[:splitindx+1]
    
    #Problem     
    else:
        artist = 'Problem'
        song = 'Change song'
   
    
    song = song.strip()
    artist = artist.strip()
    return artist,song


#returns nth substring from string
def find_nth(haystack, needle, n):
    start = haystack.find(needle)
    while start >= 0 and n > 1:
        start = haystack.find(needle, start+len(needle))
        n -= 1
    return start
    
   
    
main()